<?php
namespace app\core;

use app\core\InitController;
use app\BaseController;
use think\facade\Session;
use think\facade\Cookie;
use think\facade\Db;
use think\facade\View;
use think\facade\Request;
use think\Model;
use app\lnadmin\model\admin\Lnadmin;
use app\lnadmin\model\admin\UserToken;
use app\lnadmin\model\admin\Banner;
use app\lnadmin\model\admin\OnlineUsers;

use app\store\model\User;
use app\store\model\Navbar;
use app\store\model\Article;
/**
 * 核心控制器
 * Class InitController
 * @package app\controller\core
 */
class InitController extends BaseController
{
    use Base;

    // 后台管理员信息
    protected $admin = null;

    // 前台用户信息
    protected $user = null;

    // 初始化
    protected function initialize()
    {
        // 后台用户
        if (Session::get('token') || cookie('token')) {

            $token = cookie('token') ? cookie('token') : Session::get('token');
            $this->admin = lnadmin::checkToken($token);
            View::assign('admin',$this->admin);// 定义全局变量ADMIN
            
           if(!empty($this->admin->id)){
            $list = UserToken::where(['token' => $token])->findOrEmpty();
            if($list->expire_time <= time()){
              cookie('token',null);
              Session::delete('token'); 
             return $this->success('', 0, '身份已过期，请重新登录验证。', url('lnadmin/login'));
              }
           } 
        }  
        // 前台用户
        if (Session::get('userToken') || cookie('userToken')){
            $userToken = cookie('userToken') ?: Session::get('userToken');
            $this->user = User::checkToken($userToken);
        }
           if(!empty($this->user->id)){

        $model = UserToken::where(['token' => $userToken])->findOrEmpty();
           if($model->expire_time <= time()){
           cookie('userToken',null);
           Session::delete('userToken'); 
        return $this->success(true, 0, '请重新验证身份',url('user/login')); 
           }
            
          }
          // 获取在线人数
           OnlineUsers::onlineUserTracking();
           OnlineUsers::removeOfflineUsers();
        // 批量赋值
        View::assign([
            'user'      => $this->user,// 定义全局变量USER
             'online'    => OnlineUsers::getOnlineCount(),// 在线人数
            'cat'       => $this->Tree(Navbar::getNavbar(),0,0),// 渲染视图栏目(已缓存)
            'banner'    => Banner::banner(),// 轮播图(已缓存)
            'model'     => Article::getBase(), //随机的(1,19)
            'string'    => '#' . substr(str_shuffle(str_repeat('0123456789ABCDEF', 10)), 0, 6)//str_shuffle随机地打乱字符串中的所有字符str_repeat重复10次截取6位
        ]);
        parent::initialize(); // TODO: Change the autogenerated stub
    }
}